package com.zhkj.txg.module.mine.ui

import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.mine.adapter.CollectionGoodsAdapter
import com.zhkj.txg.module.mine.adapter.CollectionShopAdapter
import com.zhkj.txg.module.mine.vm.CollectionViewModel
import com.zhkj.txg.module.product.popup.ProductSharePopupWindow
import com.zhkj.txg.module.product.ui.ProductShareActivity
import com.zhkj.txg.module.product.ui.ShareFriendActivity
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.ShareUtils
import kotlinx.android.synthetic.main.fragment_collection.*

class CollectionGoodsFragment : ViewModelFragment<CollectionViewModel>() {

    companion object {
        val TYPE_GOODS = "goods"
        val TYPE_SHOPS = "shops"
        private val TYPE = "type"
        fun newInstance(type: String): CollectionGoodsFragment {
            return CollectionGoodsFragment().apply {
                arguments = bundleOf(Pair(TYPE, type))
            }
        }
    }

    override fun setViewModel(): CollectionViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_collection

    private val goodsAdapter = CollectionGoodsAdapter { checkStatus ->
        // adapter的item选中状态发生了变化
        RxBus.post(CollectStatusChangeEvent(viewModel.type, checkStatus))
    }.apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.collectionList(AccountManager.getToken(), CustomApplication.getShopId().toString())
        }
        setOnItemChildClickListener { _, view, position ->
            data[position].goods?.let {
                when (view.id) {
                    // 发圈素材
                    R.id.tvCollectionTagMatter -> ShareFriendActivity.open(
                        requireActivity(), it.shareContent, it.shareImages.toTypedArray()
                    )
                    // 分享赚钱
                    R.id.tvCollectionTagShareEarn -> with(sharePopupWindow) {
                        setShareEarn(if (it.shareEarn.isEmpty()) "0.0" else it.shareEarn)
                        productName = it.goodsName
                        productPrice = it.price
                        productImage = mutableListOf(it.image)
                        goodsId = it.id
                        shareUrl = it.shareUrl ?: ""
                        showPopupWindow()
                    }
                }
            }
        }
    }

    private val shopAdapter = CollectionShopAdapter { checkStatus ->
        // adapter的item选中状态发生了变化
        RxBus.post(CollectStatusChangeEvent(viewModel.type, checkStatus))
    }.apply {
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.collectionList(AccountManager.getToken(), CustomApplication.getShopId().toString())
        }
    }

    private val sharePopupWindow: ProductSharePopupWindow by lazy {
        ProductSharePopupWindow(requireContext()) { type ->
            when (type) {
                2 -> {
                    if (sharePopupWindow.productImage.isNotEmpty()) ProductShareActivity.open(
                        requireActivity(), sharePopupWindow.goodsId,
                        sharePopupWindow.productImage.toTypedArray(),
                        sharePopupWindow.productName,
                        sharePopupWindow.productPrice
                    ) else toast(getString(R.string.empty_gallery))
                }
                1 -> ShareUtils.shareUrl2Friends(
                    requireActivity(),
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl
                )
                else -> ShareUtils.shareUrl2Friends(
                    requireActivity(),
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl,
                    true
                )
            }
        }
    }

    override fun initUI() {
        // 列表页设置
        with(rvCollection) {
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            layoutManager = LinearLayoutManager(requireContext())
            adapter = if (viewModel.type == TYPE_GOODS) goodsAdapter else shopAdapter
        }
        if (viewModel.type == TYPE_GOODS) goodsAdapter.setEmptyView(R.layout.layout_empty_data)
        else shopAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshCollection.setOnRefreshListener {
            initData()
        }
    }

    override fun initViewModel() {
        // 设置当前页面的类型
        viewModel.type = arguments?.getString(TYPE) ?: TYPE_GOODS
        // 当前页面编辑模式改变观察者
        viewModel.editMode.observe(viewLifecycleOwner, Observer { editMode ->
            if (viewModel.type == TYPE_GOODS) goodsAdapter.editMode = editMode
            else shopAdapter.editMode = editMode
        })
        viewModel.cancelCollectionLiveData.observe(viewLifecycleOwner, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS)
                viewModel.collectionList(AccountManager.getToken(), CustomApplication.getShopId().toString(), true)
        })
        // 当前页面列表数据刷新观察者
        viewModel.collectionLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    if (viewModel.type == TYPE_GOODS) {
                        // 判断加载状态
                        if (!it.loadMore) refreshCollection.finishRefresh()
                        else if (it.hasMore) goodsAdapter.loadMoreModule?.loadMoreComplete()
                        else goodsAdapter.loadMoreModule?.loadMoreEnd()
                        // 数据填充
                        if (it.loadMore) goodsAdapter.addData(it.data)
                        else goodsAdapter.setNewData(it.data)
                    } else {
                        // 判断加载状态
                        if (!it.loadMore) refreshCollection.finishRefresh()
                        else if (it.hasMore) shopAdapter.loadMoreModule?.loadMoreComplete()
                        else shopAdapter.loadMoreModule?.loadMoreEnd()
                        // 数据填充
                        if (it.loadMore) shopAdapter.addData(it.data)
                        else shopAdapter.setNewData(it.data)
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    when {
                        viewModel.page <= 1 -> refreshCollection.finishRefresh(false)
                        viewModel.type == TYPE_GOODS -> goodsAdapter.loadMoreModule?.loadMoreFail()
                        else -> shopAdapter.loadMoreModule?.loadMoreFail()
                    }
                }
            }
        })
    }

    override fun initData() {
        viewModel.collectionList(AccountManager.getToken(), CustomApplication.getShopId().toString(), true)
        viewModel.editMode.value = false
    }

    /**
     * 设置当前页面的全选状态
     */
    fun checkAll(checkAll: Boolean) {
        if (viewModel.type == TYPE_GOODS) goodsAdapter.refreshCheckStatus(true, checkAll)
        else shopAdapter.refreshCheckStatus(true, checkAll)
    }

    /**
     * 切换当前页面的编辑状态
     */
    fun toggleEditMode() {
        viewModel.editMode.value = viewModel.editMode.value?.not() ?: false
        if (viewModel.type == TYPE_GOODS) goodsAdapter.loadMoreModule?.isEnableLoadMore =
            viewModel.editMode.value?.not() ?: false
        else shopAdapter.loadMoreModule?.isEnableLoadMore = viewModel.editMode.value?.not() ?: false
    }

    /**
     * 获取当前页面是否在编辑模式
     */
    fun isEditMode(): Boolean {
        return viewModel.editMode.value ?: false
    }

    /**
     * 获取当前页面的item选中状态
     */
    fun getCheckStatus(): CheckStatusEntity {
        return if (viewModel.type == TYPE_GOODS) goodsAdapter.checkStatus
        else shopAdapter.checkStatus
    }

    fun cancelCollect() {
        viewModel.cancelCollection(
            AccountManager.getToken(),
            if (viewModel.type == TYPE_GOODS) goodsAdapter.getCheckedGoodsId()
            else shopAdapter.getCheckedShopsId()
        )
    }
}

data class CheckStatusEntity(
    var allCheck: Boolean = false,
    var checkAny: Boolean = false
)